package com.zhonghan.recharge.query;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.zhonghan.common.utils.StringUtils;
import com.zhonghan.common.wechat.api.TemplateMsgApi;
import com.zhonghan.common.wechat.api.UserApi;
import com.zhonghan.common.wechat.bean.result.BaseResult;
import com.zhonghan.common.wechat.bean.template.TemplateMsg;
import com.zhonghan.common.wechat.bean.user.BaseUserInfo;
import com.zhonghan.recharge.dao.ZhGascardOrderDao;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.task.TaskList;

/**
 * 微信用户关注后执行订单查询推送
 * @author zhangceven
 *
 */
public class OrderQueryPushListener implements MessageListener{

	private Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private ZhGascardOrderDao zhGascardOrderDao;
	
	@Value("${wechat.APPID}")
	private String APPID;
	
	@Value("${wechat.APPSECRET}")
	private String APPSECRET;
	
	@Value("${wechat.DOMAIN}")
	private String DOMAIN;
	
	@Override
	public void onMessage(Message message) {
		TextMessage text = (TextMessage) message;
		
		try {
			String textMsg = text.getText();
			if(StringUtils.isNotEmpty(textMsg)){
				logger.info("收到订单消息: " + textMsg);
				orderQueryPush(textMsg);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	// 订单查询推送
	private void orderQueryPush(String textMsg) {
		SimpleDateFormat sdft = new SimpleDateFormat("yyyy-MM-dd");
		
		@SuppressWarnings("unchecked")
		Map<String,String> map = JSON.parseObject(textMsg,Map.class);
		
		String orderNo = (String) map.get("OrderNo");
		String openId = (String) map.get("OpenId");
		
		ZhGascardOrder order = null;
		if(StringUtils.isNotEmpty(orderNo)){
			order = zhGascardOrderDao.selectZhGascardOrderByOrderNo(orderNo);
			if(StringUtils.isEmpty(order.getOpenid())){
				openId = order.getOpenid();
			}
		}else{
			if(StringUtils.isNotEmpty(openId)){
				order = new ZhGascardOrder();
				order.setOpenid(openId);
				order.setOrderTime(sdft.format(new Date()));
				order.setOrderBy("orderTime");
				order.setSortBy("desc");
				PageHelper.startPage(1, 1);
				List<ZhGascardOrder> list = zhGascardOrderDao.selectZhGascardOrderByCondition(order);
				if(list.size() > 0){
					order = list.get(0);
				}else{
					return;
				}
			}
		}
		
		//Token token = TokenApi.getToken(APPID, APPSECRET);
		// 这里的access_token是临时获取的,以后需要放在缓存中
		//BaseUserInfo baseUserInfo = UserApi.getUserInfo(token.getAccess_token(), openId, "zh_CN");
		BaseUserInfo baseUserInfo = UserApi.getUserInfo(TaskList.Wechat_Access_Token, openId, "zh_CN");
		String nickname = baseUserInfo.getNickname();
		
		TemplateMsg templateMsg = TemplateMsg.New()
				.setTouser(openId)
				.setTemplate_id("u9r4mDXu49xcNNBEkbxPGDqASU9Xil2L_PF-MxlPBTQ")
				.setTopcolor("#743A3A")
				.setUrl( DOMAIN + "/recharge/oil/card/rechargeResult?orderNo=" + order.getOrderNo())
				.add("first", "您好,您已提交油卡充值订单,系统正在为您充值中", "#743A3A")
				.add("tradeDateTime", order.getOrderTime(), "#0000FF")
				.add("orderType", order.getBmItemName(), "#0000FF")
				.add("customerInfo", nickname, "#0000FF")
				.add("orderItemName", "充值金额", "#000000")
				.add("orderItemData", order.getRechargeAmount()+" 元", "#0000FF")
				.add("remark", "点击详情查看订单", "#008000");
				
		String templateMsgJson = JSON.toJSONString(templateMsg);
		
		if(StringUtils.isNotEmpty(order.getOpenid())){
			
			//BaseResult sendMessage = TemplateMsgApi.sendMessage(token.getAccess_token(), templateMsgJson);
			BaseResult sendMessage = TemplateMsgApi.sendMessage(TaskList.Wechat_Access_Token, templateMsgJson);
			logger.info("发送结果: " + JSON.toJSONString(sendMessage));
			if(sendMessage.getErrcode().equals("0")){
				logger.info("用户订单信息推送成功");
			}
		}else{
			if(StringUtils.isNotEmpty(openId)){
				BaseResult sendMessage = TemplateMsgApi.sendMessage(TaskList.Wechat_Access_Token, templateMsgJson);
				
				if(sendMessage.getErrcode().equals("0")){
					logger.info("用户订单信息推送成功");
				}
			}
			
		}
		
	}

	
	
}
